from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.forms import HiddenInput
from django.forms.forms import pretty_name
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _

from pages_images_extension.models import Image

class ImageField(HiddenInput):
    def render(self, name, value, attrs=None):
        try:
            image = Image.objects.get(id=value)
            content_type = ContentType.objects.get_for_model(Image)
            image_admin_url = reverse('admin:%s_%s_change'
                % (content_type.app_label, content_type.model),
                args=[image.id])
            rendered_hidden_field = (super(ImageField, self)
                .render(name, image.id, attrs))

            current_file = ('None' if image.image_file == ''
                else image.image_file)

            rendered_hidden_field = ''
            field_content = (_('''
            Current: %s<br/>
            <a href="%s">Change image</a>%s
            ''') % (current_file, image_admin_url, rendered_hidden_field))

        except (ObjectDoesNotExist, ValueError):
            field_content = _('Please save the page to show the image field')

        return mark_safe('''
            <div class="field-box clearfix">
                <label for="id_image_right">%s:</label>
                %s
            </div>'''
            % (pretty_name(name), field_content))
